/**
 *Project: jh-framework
 *File: cn.xkshow.util.ConvertHelper.java 
 *Author: admin@xkshow.cn with the copyrite
 ****************************************************************
 *   VERSION       DATE            BY       CHANGE/COMMENT
 * --------------------------------------------------------------
 *    1.0        2013-3-18        xkshow.cn         create
 ****************************************************************
 *note: 转换Util
 ***************************************************************/
package cn.xkshow.util;

import java.beans.PropertyDescriptor;
import java.util.Arrays;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.ResourceBundle;
import java.util.regex.Pattern;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.DynaProperty;
import org.apache.commons.logging.Log;

import cn.xkshow.lang.StringHelper;
import cn.xkshow.util.converters.DateConverter;
import cn.xkshow.util.model.LabelValue;

public final class ConvertHelper {
	private static Log log;

	static {
		//ConvertUtils.register(new DateConverter(), Date.class);
		// ConvertUtils.register(new DateConverter(), String.class);
		// ConvertUtils.register(new LongConverter(null), Long.class);
		// ConvertUtils.register(new IntegerConverter(), Integer.class);
	}

	/*
	 * Properties
	 */
	public static void copyProperties(Object target, Object o) throws Exception {
		if (o == null) {
			return;
		}

		BeanUtils.copyProperties(target, o);
	}

	public static void copyPropertiesWithoutNull(Object target, Object orig)
			throws Exception {
		if (orig == null) {
			return;
		}

		BeanUtilsBean beanUtilsBean = BeanUtilsBean.getInstance();
		Object origT = null, oValue = null;
		String name = "";
		if ((orig instanceof DynaBean)) {
			DynaProperty[] origDescriptors = ((DynaBean) orig).getDynaClass()
					.getDynaProperties();
			for (int i = 0; i < origDescriptors.length; i++) {
				name = origDescriptors[i].getName();

				if ((!beanUtilsBean.getPropertyUtils().isReadable(orig, name))
						|| (!beanUtilsBean.getPropertyUtils().isWriteable(
								target, name)))
					continue;
				oValue = ((DynaBean) orig).get(name);
				if (null != oValue)
					beanUtilsBean.copyProperty(target, name, oValue);
			}
		} else if ((orig instanceof Map)) {
			Iterator entries = ((Map) orig).entrySet().iterator();
			while (entries.hasNext()) {
				Map.Entry entry = (Map.Entry) entries.next();
				name = (String) entry.getKey();
				if (beanUtilsBean.getPropertyUtils().isWriteable(target, name)) {
					if (null != entry.getValue())
						beanUtilsBean.copyProperty(target, name, entry
								.getValue());
				}
			}
		} else {
			PropertyDescriptor[] origDescriptors = beanUtilsBean
					.getPropertyUtils().getPropertyDescriptors(orig);			
			for (int i = 0; i < origDescriptors.length; i++) {
				name = origDescriptors[i].getName();
				if ("class".equals(name)) {
					continue;
				}
				if ((!beanUtilsBean.getPropertyUtils().isReadable(orig, name))
						|| (!beanUtilsBean.getPropertyUtils().isWriteable(
								target, name)))
					continue;
				try {
					oValue = beanUtilsBean.getPropertyUtils()
							.getSimpleProperty(orig, name);
					if (null != oValue)
						beanUtilsBean.copyProperty(target, name, oValue);
				} catch (NoSuchMethodException e) {
				}
			}
		}
	}

	public static Properties convertBundleToProperties(ResourceBundle rb) {
		Properties props = new Properties();

		for (Enumeration keys = rb.getKeys(); keys.hasMoreElements();) {
			String key = (String) keys.nextElement();
			props.put(key, rb.getString(key));
		}

		return props;
	}

	public static Object populateObject(Object obj, ResourceBundle rb) {
		Map map;
		try {
			map = convertBundleToMap(rb);

			BeanUtils.copyProperties(obj, map);
		} catch (Exception e) {
			e.printStackTrace();
			log.error("Exception occured populating object: " + e.getMessage());
		}

		return obj;
	}

	/*
	 * Map
	 */
	public static Map convertBundleToMap(ResourceBundle rb) {
		Map map = new HashMap();

		for (Enumeration keys = rb.getKeys(); keys.hasMoreElements();) {
			String key = (String) keys.nextElement();
			map.put(key, rb.getString(key));
		}

		return map;
	}

	public static Map convertListToMap(List list) {
		Map map = new LinkedHashMap();

		for (Iterator it = list.iterator(); it.hasNext();) {
			LabelValue option = (LabelValue) it.next();
			map.put(option.getLabel(), option.getValue());
		}

		return map;
	}

	/*
	 * String-Array
	 * 
	 * @splite: default ','
	 */
	public static String ary2String(Object ary[], String splite) {
		String arraystr = null;
		if (ary != null) {
			arraystr = Arrays.toString(ary);
			arraystr = arraystr.substring(1, arraystr.length() - 1);
			arraystr = Pattern.compile("\\s*|\t|\r|\n").matcher(arraystr)
					.replaceAll("");
			if (StringHelper.isNotNull(splite)) {
				arraystr = arraystr.replaceAll(",", splite);
				arraystr = arraystr.startsWith(splite) ? arraystr
						.substring(splite.length()) : arraystr;
				arraystr = arraystr.endsWith(splite) ? arraystr.substring(0,
						arraystr.length() - splite.length()) : arraystr;
			} else {
				arraystr = arraystr.startsWith(",") ? arraystr.substring(1)
						: arraystr;
				arraystr = arraystr.endsWith(",") ? arraystr.substring(0,
						arraystr.length() - 1) : arraystr;
			}
		}
		return arraystr;
	}

	public static Object[] string2Ary(String arraystr, String splite) {
		if (StringHelper.isNotNull(arraystr)) {
			arraystr = Pattern.compile("\\s*|\t|\r|\n").matcher(arraystr)
					.replaceAll("");
			if (StringHelper.isNotNull(splite)) {
				arraystr = arraystr.startsWith(splite) ? arraystr
						.substring(splite.length()) : arraystr;
				arraystr = arraystr.endsWith(splite) ? arraystr.substring(0,
						arraystr.length() - splite.length()) : arraystr;
				return arraystr.split(splite);
			} else {
				arraystr = arraystr.startsWith(",") ? arraystr.substring(1)
						: arraystr;
				arraystr = arraystr.endsWith(",") ? arraystr.substring(0,
						arraystr.length() - 1) : arraystr;
				return arraystr.split(",");
			}
		} else {
			return null;
		}
	}

}
